package com.graduation_design.modules.system.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.graduation_design.common.dto.LoginDto;
import com.graduation_design.common.lang.Result;
import com.graduation_design.entity.SysUser;
import com.graduation_design.modules.system.shiro.AccountProfile;
import com.graduation_design.service.SysMenuService;
import com.graduation_design.service.SysUserService;
import com.graduation_design.utils.JwtUtils;
import com.graduation_design.utils.ShiroUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/sys")
public class SysLoginController {

    @Resource
    SysUserService sysUserService;

    @Resource
    JwtUtils jwtUtils;

    @Resource
    SysMenuService sysMenuService;

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto) {

        // 校验用户名密码
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", loginDto.getUsername()));
        Assert.notNull(sysUser, "用户名或密码错误");

        if (!sysUser.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
            return Result.fail("用户名或密码错误");
        }

        // 生成token
        String token = jwtUtils.generateToken(sysUser.getId(), "ADMIN");
        return Result.success(MapUtil.builder()
                .put("token", token)
                .build()
        );
    }

    /**
     * 返回基本信息
     */
    @GetMapping("/userInfo")
    public Result userInfo() {
        AccountProfile profile = ShiroUtil.getProfile();

        // menus是可操作的菜单，比如角色管理，用户管理等
        // auths是可以执行的权限，比如：sys:user:save等等
        return Result.success(MapUtil.builder()
                .put("userInfo", profile)
                .put("menus", sysMenuService.getCurrentUserNav()) // 获取菜单
                .put("auths", sysMenuService.getUserPerms(profile.getId())) // 获取权限: sys:user:save
                .map());
    }
}
